//
//  DetailViewController.m
//  LimitFree
//
//  Created by LZXuan on 15-6-26.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "DetailViewController.h"
#import "DetailModel.h"
#import "AFNetworking.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "PhotoViewController.h"
#import "UMSocial.h"
//系统自带的
#import <MessageUI/MessageUI.h>

@interface DetailViewController ()<UIActionSheetDelegate,MFMessageComposeViewControllerDelegate,MFMailComposeViewControllerDelegate,UMSocialDataDelegate,UMSocialUIDelegate>
{
    //存放附近的人信息
    NSMutableArray *_modelsArr;
}
//附近的人使用
@property (nonatomic,strong) NSMutableArray *modelsArr;
//存放详情
@property (nonatomic,strong) DetailModel *detailModel;

@property (weak, nonatomic) IBOutlet UIImageView *iconImageview;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
- (IBAction)sharedClick:(UIButton *)sender;
- (IBAction)favoriteClick:(id)sender;

- (IBAction)downloadClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIScrollView *photoScrollView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIScrollView *appScrollView;

@end

@implementation DetailViewController

//详情界面 有两个接口 一个详情的接口 一个是周边的人接口
//必须下载完成数据之后 才可以 去填充 详情界面

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitleViewWithTitle:@"应用详情"];
    [self downloadDetailData];
    [self downloadNearData];
}
#pragma mark - 下载详情数据
- (void)downloadDetailData {
    NSString *url = [NSString stringWithFormat:kDetailUrl,self.applicationsId];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //只下载 不解析
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"详情下载成功");
        if (responseObject) {
            //json
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            self.detailModel = [[DetailModel alloc] init];
            //保存到model
            [self.detailModel setValuesForKeysWithDictionary:dict];
            //填充详情
            [self showDataWithDetail:self.detailModel];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"详情下载失败");
    }];
}
- (void)showDataWithDetail:(DetailModel *)model {
    [self.iconImageview sd_setImageWithURL:[NSURL URLWithString:model.iconUrl] placeholderImage:[UIImage imageNamed: @"topic_Header"]];
    self.nameLabel.text = model.name;
    NSString *type = nil;
    if ([self.categoryType isEqualToString:kLimitType]) {
        type = @"限免中";
    }else if ([self.categoryType isEqualToString:kReduceType]){
         type = @"降价中";
    }else if ([self.categoryType isEqualToString:kFreeType]){
        type = @"免费中";
    }else {
        type = @"热榜中";
    }
    
    self.priceLabel.text = [NSString stringWithFormat:@"原价:%@ %@ %@MB",model.lastPrice,type,model.fileSize];
    self.typeLabel.text = [NSString stringWithFormat:@"类型:%@ 评分%@",model.categoryName,model.starOverall];
    self.textView.text = model.description;
    //滚动视图的五张图片
    
    CGFloat h = self.photoScrollView.frame.size.height;
    
    CGFloat space = 5;
    CGFloat w = (self.photoScrollView.frame.size.width - 6*space)/5;
    for (NSInteger i = 0; i < model.photos.count; i++) {
        
        NSDictionary *dict = model.photos[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(space+(w+space)*i, 0, w, h);
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:dict[@"smallUrl"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed: @"topic_Header"]];
        button.tag = 101+i;
        [self.photoScrollView addSubview:button];
    }
    //设置滚动视图 滚动范围
    self.photoScrollView.contentSize = CGSizeMake(model.photos.count * (space +w)+20, self.photoScrollView.frame.size.height);
    
}
#pragma mark - 图片被点击
- (void)btnClick:(UIButton *)button {
    PhotoViewController *photo = [[PhotoViewController alloc] init];
    photo.photos = self.detailModel.photos;
    //被选中的图片索引
    photo.selectIndex = button.tag-101;
    photo.hidesBottomBarWhenPushed = YES;
    //跳转
    [self.navigationController pushViewController:photo animated:YES];
    
}

#pragma mark - 下载附近数据
- (void)downloadNearData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    double longitude =  116.344539;
    double latitude = 40.034346;
    NSString *nearUrl = [NSString stringWithFormat:kNearAppUrl,longitude,latitude];
    
    
    __weak typeof(self) weakSelf = self;
    [manager GET:nearUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = dict[@"applications"];
            weakSelf.modelsArr = [[NSMutableArray alloc] init];
            
            NSInteger width = (weakSelf.appScrollView.bounds.size.width - 5*6)/5;
            NSInteger height = weakSelf.appScrollView.bounds.size.height;
            for (NSInteger i = 0; i < arr.count; i++) {
                AppModel *model = [[AppModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:arr[i]];
                [weakSelf.modelsArr addObject:model];
                
                //创建里面的button
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame =CGRectMake(5+(width+5)*i, 0, width, height);
                [button addTarget:self action:@selector(iconClick:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = 301+i;
                //异步加载网络图片
                [button sd_setBackgroundImageWithURL:[NSURL URLWithString:model.iconUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed: @"topic_Header"]];
                button.layer.masksToBounds = YES;
                button.layer.cornerRadius = 8;
                
                [weakSelf.appScrollView addSubview:button];
            }
            //设置 滚动区域范围
            weakSelf.appScrollView.contentSize = CGSizeMake(weakSelf.appScrollView.bounds.size.width+20, height);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"附近的人下载失败");
    }];
    
}
#pragma mark - 附近的人按钮
- (void)iconClick:(UIButton *)button {
    //获取选中的 应用model
    AppModel *model = _modelsArr[button.tag-301];
    //详情跳转
    DetailViewController *detail = [[DetailViewController alloc] init];
    //传值
    detail.applicationsId = model.applicationId;
    detail.categoryType = self.categoryType;
    
    [self.navigationController pushViewController:detail animated:YES];
}


#pragma mark - 三个按钮
- (IBAction)sharedClick:(UIButton *)sender {
#if 1
    //方法3：友盟
    //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
    //如果需要分享回调，请将delegate对象设置self，并实现下面的回调方法
    NSString *text = [NSString stringWithFormat:@"hhhhhhshshhahs%@",self.detailModel.itunesUrl];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:text
                                     shareImage:[UIImage imageNamed:@"account_candou"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToQQ,UMShareToWechatTimeline,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];

#elif 0
    //方法2：系统自带的  调用 视图控制器（包含短信模块和邮箱模块）
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"分享" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"短信",@"邮箱", nil];
    [sheet showInView:self.view];

#else
    //方法1 调用系统的APP
    //添加表单
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"分享" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"短信",@"邮箱",@"电话", nil];
    [sheet showInView:self.view];
#endif
}
#if 1
//方法3：友盟

//弹出列表方法presentSnsIconSheetView需要设置delegate为self
-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}

//实现回调方法（可选）:

-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}


#elif 0
//方法2：系统自带的  调用 视图控制器（包含短信模块和邮箱模块）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //短信
            //1 导入头文件 #import <MessageUI/MessageUI.h>
            //2 判断是否支持发送短信
            if ([MFMessageComposeViewController canSendText]) {
                //创建一个 MFMessageComposeViewController  是一个导航视图控制器内部 包含短信模块
                MFMessageComposeViewController *message = [[MFMessageComposeViewController alloc] init];
                //设置标题
                message.subject = @"分享内容";
                //设置联系人 可以群发
                message.recipients = @[@"10086",@"10010"];
                //设置  内容
                //分享链接
                NSString *body = [NSString stringWithFormat:@"点击有惊喜哟%@",self.detailModel.itunesUrl];
                message.body = body;
                //增加附件
                //message addAttachmentData:(NSData *) typeIdentifier:(NSString *) filename:(NSString *)
                //设置代理
                message.messageComposeDelegate = self;
                
                //跳转 模态跳转
                [self presentViewController:message animated:YES completion:nil];
                
            }else{
                NSLog(@"不支持短信");
            }
            break;
        case 1:
            //邮箱
            if([MFMailComposeViewController canSendMail]){
                MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
                //设置 标题 联系人 内容  增加附件
                [mail setSubject:@""];
                [mail setToRecipients:@[@"",@""]];
                NSString *body = [NSString stringWithFormat:@"点击有惊喜哟%@",self.detailModel.itunesUrl];
                [mail setMessageBody:body isHTML:YES];//是否采用HTML格式
                NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"account_candou"]);
                [mail addAttachmentData:data mimeType:@"image/png" fileName:@"account_candou"];
                //设置代理
                mail.mailComposeDelegate =self;
                //模态跳转
                [self presentViewController:mail animated:YES completion:nil];
            }else{
                NSLog(@"暂时不支持邮箱");
            }
            break;
            default:
            break;
    }
}
#pragma mark - MFMessageComposeViewControllerDelegate协议方法
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    switch (result) {
        case MessageComposeResultCancelled:{
            NSLog(@"取消发送");
        }
            break;
        case MessageComposeResultFailed:{
            NSLog(@"发送成功");
        }
            break;
        case MessageComposeResultSent:{
            NSLog(@"发送失败");
        }
            break;
        default:
            break;
    }
    //最后要模态跳转返回的
    [controller dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -MFMailComposeViewControllerDelegate协议方法
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    switch (result) {
        case MFMailComposeResultCancelled:
        {
        
        }
            break;
        case MFMailComposeResultSaved:
        {
            
        }
            break;
        case MFMailComposeResultSent:
        {
            
        }
            break;
        case MFMailComposeResultFailed:
        {
            
        }
            break;
        default:
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}
#else
//方法1 调用系统的APP
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //短信
            //调用系统的短信App/应用  openURL
            //可以调用 其他的app
            //只需要知道 app 的scheme
            //@"sms://10086"短信
            //@"tel://10086"打电话
            //@"mailto://88668990@qq.com"调用邮箱
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://10086"]];
            break;
            case 1:
            //邮箱
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://88668990@qq.com"]];
            break;
            case 2:
            //电话
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];
            break;
        default:
            break;
    }
}
#endif
- (IBAction)favoriteClick:(id)sender {
}

- (IBAction)downloadClick:(UIButton *)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.detailModel.itunesUrl]];
}
@end



